package com.gljx.web.controller;

import com.gljx.util.*;
import com.gljx.web.Entity.*;
import com.gljx.web.dao.CoachsubMapper;
import com.gljx.web.service.CoachSubService;
import com.gljx.web.service.CustomLogService;
import com.gljx.web.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Author lcx
 * @Date 2017/12/14 0014 上午 8:45
 */
@Controller
@RequestMapping("/")
public class CoachSubContraller {

    @Autowired
    CoachSubService coachSubService;
    @Autowired
    DepartmentService departmentService;
    @Autowired
    CustomLogService customLogService;
    @Autowired
    PersonController personController;
    @Autowired
    StudentController studentController;
    @Autowired
    CoachsubMapper coachsubMapper;

    /**
     * @Author lcx
     * @Date 2017/12/14 0014 上午 8:45
     */
    @RequestMapping("/queryCoachSub/look.action")
    public String queryCoachSub(HttpServletRequest request, @RequestParam(value = "fnumber", defaultValue = "") String fnumber
            , @RequestParam(value = "cfcoachno", defaultValue = "") String cfcoachno
            , @RequestParam(value = "jlName", defaultValue = "") String jlName
            , @RequestParam(value = "beginTime", defaultValue = "") String beginTime
            , @RequestParam(value = "endTime", defaultValue = "") String endTime
            , @RequestParam(value = "state", defaultValue = "") String state
            , @RequestParam(value = "alertType", defaultValue = "") String alertType) {


        PageBean<Coachsub> pb = new PageBean<>();
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        try {
            fnumber = fnumber.trim();//去空格
            cfcoachno = cfcoachno.trim();
            jlName = jlName.trim();
            //第一次进来
            if ("first".equals(state)) {
                beginTime = TimeFormat.getMonth();
                endTime = TimeFormat.getNowTime();
                pb = getPageBean(request, user.getFcompanyid(), fnumber, cfcoachno, jlName, beginTime, endTime, "");
            } else if ("".equals(state) && "".equals(beginTime) || "".equals(endTime)) {
                pb = getPageBean(request, user.getFcompanyid(), fnumber, cfcoachno, jlName, beginTime, endTime, null);
            } else {
                //获取分页  如果编码为空默认按照业务日期排序分页显示
                pb = getPageBean(request, user.getFcompanyid(), null, cfcoachno, jlName, beginTime, endTime, "");
            }
            //计数器
            int i = 0;
            //缓存需要删除的序列
            List<Integer> tem = new ArrayList<>();
            //获取当前分页的值
            List<Coachsub> coachsubList = pb.getBeanList();
            /*合计信息条数*/
            String messageAmount="共有"+pb.getTr()+"条信息";
            //返回界面的搜索条件
            request.setAttribute("messageAmount",messageAmount);
            request.setAttribute("fnumber", fnumber);
            request.setAttribute("cfcoachno", cfcoachno);
            request.setAttribute("jlName", jlName);
            request.setAttribute("beginTime", beginTime);
            request.setAttribute("endTime", endTime);

            request.setAttribute("coachsubList", coachsubList);
            request.setAttribute("pb", pb);
            request.setAttribute("alertType", alertType);


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "/backHome/CoachManagement/Coachsub/CoachSubList";
    }

    /**
     * @Author lcx
     * @Date 2017/12/14 0014 上午 8:45
     */
    public PageBean<Coachsub> getPageBean(HttpServletRequest request, String companyId, String fnumber,
                                          String cfcoachno, String jlName,
                                          String beginTime, String endTime,
                                          String state) throws Exception {

        int offset;//从第几条数据开始加载
        if (request.getParameter("pager.offset") == null) {
            offset = 0;
        } else {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        //拼接SQL语句
        StringBuffer psql = new StringBuffer();
        if (state == null) {
            psql.append("SELECT c.fid," +
                    "  c.FNUMBER, " +
                    "  to_char(c.FBIZDATE, 'yyyy-mm-dd') fbizdate, " +
                    "  c.FDESCRIPTION, " +
                    "  u.NAME                            createName, " +
                    "  u2.NAME                           checkName, " +
                    "  c.CFBILLSTATE, " +
                    "  p.FNAME_L2 jlName, " +
                    "  c2.CFJIAOLIANNO, " +
                    "  c2.CFDQSUB, " +
                    "  c2.CFDESC, " +
                    "  c2.CFDQCARTYPE, " +
                    "  c2.CFXZCARTYPE, " +
                    "  c2.CFXZSUB " +
                    "FROM CT_DS_COACHSUB c LEFT JOIN CT_DS_COACHSUBENTRY c2 ON c.fid = c2.FPARENTID " +
                    "  LEFT JOIN T_E_USER u ON c.FCREATORID = u.FID " +
                    "  LEFT JOIN T_E_USER u2 ON c.FAUDITORID = u2.fid " +
                    "  LEFT JOIN CT_DS_PERSON p ON c2.cfjiaolianid = p.fid");
            psql.append(" where c.FCONTROLUNITID= '" + companyId + "' ");
            if (!"".equals(jlName) || jlName != null) {
                psql.append("and p.FNAME_L2 LIKE '%" + jlName + "%' ");
            }
            if (!"".equals(cfcoachno) || cfcoachno != null) {
                psql.append(" AND c2.CFJIAOLIANNO LIKE '%" + cfcoachno + "%' ");
            }
            psql.append(" ORDER BY c.FCREATETIME DESC");
        } else {
            psql.append("SELECT c.fid," +
                    "  c.FNUMBER, " +
                    "  to_char(c.FBIZDATE, 'yyyy-mm-dd') fbizdate, " +
                    "  c.FDESCRIPTION, " +
                    "  u.NAME                            createName, " +
                    "  u2.NAME                           checkName, " +
                    "  c.CFBILLSTATE, " +
                    "  p.FNAME_L2 jlName, " +
                    "  c2.CFJIAOLIANNO, " +
                    "  c2.CFDQSUB, " +
                    "  c2.CFDESC, " +
                    "  c2.CFDQCARTYPE, " +
                    "  c2.CFXZCARTYPE, " +
                    "  c2.CFXZSUB " +
                    "FROM CT_DS_COACHSUB c LEFT JOIN CT_DS_COACHSUBENTRY c2 ON c.fid = c2.FPARENTID " +
                    "  LEFT JOIN T_E_USER u ON c.FCREATORID = u.FID " +
                    "  LEFT JOIN T_E_USER u2 ON c.FAUDITORID = u2.fid " +
                    "  LEFT JOIN CT_DS_PERSON p ON c2.cfjiaolianid = p.fid");
            psql.append(" where c.FCONTROLUNITID= '" + companyId + "' ");
            if (!"".equals(jlName) || jlName != null) {
                psql.append("and p.FNAME_L2 LIKE '%" + jlName + "%' ");
            }
            if (!"".equals(cfcoachno) || cfcoachno != null) {
                psql.append(" AND c2.CFJIAOLIANNO LIKE '%" + cfcoachno + "%' ");
            }
            psql.append(" AND (c.FBIZDATE BETWEEN to_date('" + beginTime + "', 'YYYY/MM/DD') AND to_date('" + endTime + "', 'YYYY/MM/DD'))" +
                    "  ORDER BY c.FCREATETIME DESC");
        }

        int psize = 25; //每页显示数
        int pindex = offset / psize;//+1  页码从0开始
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = coachSubService.selectPage(pindex, psql.toString(), psize);
        PageBean<Coachsub> pb = new PageBean<>();
        pb.setPc(pindex); //页码
        Map<String, Object> paramMapCount = getPageBeanCount(psql.toString()); //取记录总数
        pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
        pb.setPs(psize);
        pb.setBeanList((List<Coachsub>) paramMap.get("v_cur")); //每页数据集
        return pb;
    }

    /**
     * @Author lcx
     * @Date 2017/12/14 0014 上午 8:45
     */
    public Map<String, Object> getPageBeanCount(String psql) throws Exception {

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = coachSubService.selectPageCount(psql);
        return paramMap;
    }

    @RequestMapping(value = "/go_add_Coachsub")
    public String goAddCoachsub(HttpServletRequest request, String alertType) throws Exception {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());

        /*String number = customLogService.selectFunmber("CT_DS_COACHSUB",user.getFcompanyid());*/
        String fnumber = GetFnumber.fnumbers("JLHKM");

        //查询教练弹窗信息
        Map map1 = personController.getPageAsJl(request, "", "", "0");

        request.setAttribute("beginTime", TimeFormat.getMonth());
        request.setAttribute("endTime", TimeFormat.getNowTime());

        request.setAttribute("flag", "1");
        request.setAttribute("fbizdate", TimeFormat.getNowTime());
        request.setAttribute("createName", user.getName());
        request.setAttribute("fnumber", fnumber);
        request.setAttribute("department", department.getFnameL2());
        request.setAttribute("pb1", map1.get("pb"));
        request.setAttribute("persons", map1.get("sList"));
        request.setAttribute("time", TimeFormat.getNowTime());

        request.setAttribute("alertType", alertType);


        return "/backHome/CoachManagement/Coachsub/detailCoachSub";

    }


    @RequestMapping(value = "/add_Coachsub")
    public String addCoachsub(HttpServletRequest request, Coachsub coachsub, @RequestParam(defaultValue = "0") String state) {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        //公司id
        coachsub.setCfficompanyid(user.getFcompanyid());
        //控制单元id
        coachsub.setFcontrolunitid(user.getFcompanyid());
        //获取当前修改时间
        String createTime = TimeFormat.timeFormat(new Date());
        //创建时间
        coachsub.setFcreatetime(createTime);
        //修改时间
        coachsub.setFcreatorid(user.getFid());

        //收集子类信息
        String[] cfcoachid = request.getParameterValues("cfcoachid");
        String[] cfcoachno = request.getParameterValues("cfcoachno");
        String[] cfdqsub = request.getParameterValues("cfdqsub");
        String[] cfdqcartype = request.getParameterValues("cfdqcartype");
        String[] cfxzsub = request.getParameterValues("cfxzsub");
        String[] cfxzcartype = request.getParameterValues("cfxzcartype");
        String[] cfdesc = request.getParameterValues("cfdesc");


        //添加练车  一个事物处理
        coachSubService.addCoachsub(state, coachsub, cfcoachid, cfcoachno, cfdqsub,
                cfdqcartype, cfxzsub, cfxzcartype, cfdesc);


        //添加日志
        customLogService.addLog("教练管理", TimeFormat.timeFormat(new Date()) + "对教练换科目新增", null, user.getFid());


        return "redirect:/DrivingSys/go_add_Coachsub?alertType=bc";
    }

    @RequestMapping(value = "go_update_Coachsub")
    public String goUpdateCoachsub(HttpServletRequest request, String fid, String xqid) throws Exception {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());

        //查询教练弹窗信息
        Map map1 = personController.getPageAsJl(request, "", "", "0");

        //查询换教练信息
        Coachsub coachsub = coachSubService.selectCoachsubByFid(fid);

        if (coachsub == null) {
            return "/error/not_data";
        }

        //查询是否是经办人
        Axamine axamine = new Axamine();
        request.setAttribute("AuditState", axamine.selectAuditPerson(coachsub.getFnumber()));

        request.setAttribute("beginTime", TimeFormat.getMonth());
        request.setAttribute("endTime", TimeFormat.getNowTime());

        request.setAttribute("flag", "2");
        request.setAttribute("createName", user.getName());
        request.setAttribute("department", department.getFnameL2());
        request.setAttribute("pb1", map1.get("pb"));
        request.setAttribute("persons", map1.get("sList"));
        request.setAttribute("coachsub", coachsub);

        return "/backHome/CoachManagement/Coachsub/detailCoachSub";
    }

    @RequestMapping(value = "/update_CoachSub")
    public String updateCoachSub(HttpServletRequest request, Coachsub coachsub) {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");

        //获取当前修改时间
        String createTime = TimeFormat.timeFormat(new Date());
        //修改时间
        coachsub.setFlastupdatetime(createTime);
        //修改人id
        coachsub.setFlastupdateuserid(user.getFid());


        addCoachsub(request, coachsub, "1");

        customLogService.addLog("教练管理", TimeFormat.timeFormat(new Date()) + "对教练换科目进行更新", null, user.getFid());

        return "redirect:/DrivingSys/queryCoachSub/look.action?state=first&alertType=qd";
    }

    @RequestMapping(value = "delete_Coachsub")
    public String deleteCoachsub(HttpServletRequest request, String[] deleteId, String[] fnumber) throws Exception {

        User user = (User) request.getSession().getAttribute("user");

        coachSubService.deleteByCoachsubKey(deleteId,fnumber);
        //添加日志
        customLogService.addLog("教练管理", TimeFormat.timeFormat(new Date()) + "对教练换科目进行删除", null, user.getFid());


        return "redirect:/DrivingSys/queryCoachSub/look.action?state=first";
    }

    /**
     * @Author lcx
     * @Date 2018/2/6 0006 下午 1:58
     * 流程
     */
    @RequestMapping(value = "/queryCoachSubExamine")
    @ResponseBody
    public ServerResponse examine(HttpServletRequest request, @RequestParam(defaultValue = "", value = "fid") String fid,
                                  @RequestParam(defaultValue = "", value = "state") String state,
                                  @RequestParam(defaultValue = "", value = "agreed") String agreed,
                                  @RequestParam(defaultValue = "", value = "auditcomment") String auditcomment,
                                  @RequestParam(defaultValue = "", value = "fnumber") String fnumber) {
        Coachsub coachsub = new Coachsub();

        coachsub.setFid(fid);
        coachsub.setFnumber(fnumber);

        return coachSubService.examine(coachsub, state, agreed, auditcomment);
    }

    /**
     * @Author lcx
     * @Date 2018/2/27 0027 上午 11:49
     * 提交
     */
    @RequestMapping(value = "/queryCoachSubSubmit")
    @ResponseBody
    public ServerResponse submit(HttpServletRequest request,
                                 @RequestParam(defaultValue = "", value = "fnumber") String fnumber,
                                 @RequestParam(defaultValue = "", value = "fid") String fid) {
        Axamine axamine = new Axamine();
        Coachsub coachsub = new Coachsub();

        coachsub.setFid(fid);
        /* coachsub.setFauditorid(((User) request.getSession().getAttribute("user")).getFid());*/
        coachsub.setCfbillstate(Long.valueOf("4"));
        coachsubMapper.updateByPrimaryKeySelective(coachsub);
        return axamine.submissionProcess(String.valueOf(fnumber));
    }

    @RequestMapping("/queryCoachSubXls")
    public String queryCoachSubXls(HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam(defaultValue = "", value = "jlName") String jlName,
                                   @RequestParam(defaultValue = "", value = "cfcoachno") String cfcoachno,
                                   @RequestParam(defaultValue = "", value = "beginTime") String beginTime,
                                   @RequestParam(defaultValue = "", value = "endTime") String endTime) {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");

        //头部数据
        List<Object> data = new ArrayList<>();
        String head[] = {"单据编号", "业务日期", "参考消息", "审核人名称", "制单人名称", "单据状态", "教练", "教练编码", "原教学科目", "原来车型",
                "备注", "现在学科目", "现在车型"
        };
        //长度
        Integer length[] = {8500, 5000, 6000, 3000, 3000, 3000, 3000, 3000, 4000, 3000,
                6000, 3000, 3000};

        List<Coachsub> coachsubList = coachSubService.selectCoachSubAsXls(jlName, cfcoachno, beginTime, endTime, user.getFcompanyid());


        for (Coachsub coachsub : coachsubList) {
            data.add(coachsub.getFnumber());
            data.add(coachsub.getFbizdate());
            data.add(coachsub.getFdescription());
            data.add(coachsub.getCheckName());
            data.add(coachsub.getCreateName());
            data.add(stateToString.billsState(coachsub.getCfbillstate()));
            data.add(coachsub.getJlName());//练车时间
            data.add(coachsub.getCfjiaolianno());
            data.add(stateToString.subject(coachsub.getCfdqsub()));//原教学科目
            data.add(coachsub.getCfdqcartype());//原来车型
            data.add(coachsub.getCfdesc());//备注
            data.add(stateToString.subject(coachsub.getCfxzsub()));//现教学科目
            data.add(coachsub.getCfxzcartype());//现在车型
        }

        try {
            //导出Excel
            CommonExport.importExcel(response, "教练换科目" + TimeFormat.getNowTime2() + ".xls", "教练换科目", data, head, length);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "redirect:/DrivingSys/queryCoachSub/look.action?state=first";
    }
}
